package azlog

import (
	"fmt"
	"runtime"
	"time"
)

type TLogLevel int

const (
	LOG_LEVEL_TRACE TLogLevel = iota // 无颜色
	LOG_LEVEL_DEBUG                  // 蓝色
	LOG_LEVEL_INFO                   // 绿色
	LOG_LEVEL_WARN                   // 黄色
	LOG_LEVEL_ERROR                  // 红色
)

func logPrint(level TLogLevel, data string) {
	if level > LOG_LEVEL_TRACE {
		switch level {
		case LOG_LEVEL_DEBUG:
			fmt.Print("\033[36m")
		case LOG_LEVEL_INFO:
			fmt.Print("\033[32m")
		case LOG_LEVEL_WARN:
			fmt.Print("\033[33m")
		case LOG_LEVEL_ERROR:
			fmt.Print("\033[31m")
		}
		fmt.Print(data)
		fmt.Print("\033[0m")
	} else {
		fmt.Print(data)
	}
	fmt.Print("\n")
}

func levelToString(level TLogLevel) string {
	switch level {
	case LOG_LEVEL_DEBUG:
		return "D"
	case LOG_LEVEL_INFO:
		return "I"
	case LOG_LEVEL_WARN:
		return "W"
	case LOG_LEVEL_ERROR:
		return "E"
	default:
		return "T"
	}
}

func getCallerInfo(skip int) (string, int) {
	_, file, line, ok := runtime.Caller(skip)
	if !ok {
		return "???", 0
	}
	// 提取文件名（去掉完整路径）
	shortFile := file
	for i := len(file) - 1; i >= 0; i-- {
		if file[i] == '\\' || file[i] == '/' {
			shortFile = file[i+1:]
			break
		}
	}
	return shortFile, line
}

func logFormat(level TLogLevel, format string, args ...interface{}) string {
	file, line := getCallerInfo(3) // skip=3 表示跳过当前函数和调用 LOG 的函数
	// 获取当前时间
	now := time.Now()

	// 格式化时间：yy-MM-dd HH:mm:ss.ms
	timeStr := now.Format("06-01-02 15:04:05.000")

	// 格式化日志级别
	levelStr := levelToString(level)

	// 格式化日志内容
	logContent := fmt.Sprintf(format, args...)

	// 组装完整日志
	logEntry := fmt.Sprintf("[%s %s:%d@%s] %s", timeStr, file, line, levelStr, logContent)

	return logEntry
}

func LOG(level TLogLevel, format string, args ...interface{}) {
	logPrint(level, logFormat(level, format, args...))
}

func LOG_T(format string, args ...interface{}) {
	logPrint(LOG_LEVEL_TRACE, logFormat(LOG_LEVEL_TRACE, format, args...))
}
func LOG_D(format string, args ...interface{}) {
	logPrint(LOG_LEVEL_DEBUG, logFormat(LOG_LEVEL_DEBUG, format, args...))
}
func LOG_I(format string, args ...interface{}) {
	logPrint(LOG_LEVEL_INFO, logFormat(LOG_LEVEL_INFO, format, args...))
}
func LOG_W(format string, args ...interface{}) {
	logPrint(LOG_LEVEL_WARN, logFormat(LOG_LEVEL_WARN, format, args...))
}
func LOG_E(format string, args ...interface{}) {
	logPrint(LOG_LEVEL_ERROR, logFormat(LOG_LEVEL_ERROR, format, args...))
}
